﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.IO;
using System.Windows.Media.Imaging;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace TED
{
    public partial class MainPage : PhoneApplicationPage
    {
        public List<TEDVideo> items = new List<TEDVideo>();

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded +=new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
            //BitmapImage bi = new BitmapImage();
            //bi.UriSource = new Uri("http://images.ted.com/images/ted/0b1ac54b10deccf80a119a19733df65d27652489_132x99.jpg");
            //image1.Stretch = Stretch.Fill;
            //image1.Source = bi;

            ParseTEDTalks();

            //For testing purpose
            XDocument data = XDocument.Load("Data.xml");


            var persons = from query in data.Descendants("video")
                          select new TEDVideo
                          {
                              Title = (string)query.Element("title"),
                              Url = (string)query.Element("url"),
                              ImageUrl = new Uri((string)query.Element("image"), UriKind.Absolute)
                          };


            listBox2.ItemsSource = persons;
            //listBox2.ItemsSource = items;
            //listBox2.UpdateLayout();
            


        }

        /// <summary>
        /// Class TEDVideo
        /// </summary>
        public class TEDVideo
        {
            Uri imageUrl;
            string title;
            string url;

            public Uri ImageUrl
            {
                get { return imageUrl; }
                set { imageUrl = value; }
            }

            public string Title
            {
                get { return title; }
                set { title = value; }
            }

            public string Url
            {
                get { return url; }
                set { url = value; }
            }

        }

        /// <summary>
        /// The background thread fro sending the url request
        /// </summary>
        public void ParseTEDTalks()
        {
            // Create the web request object
            try
            {

                string TEDUrl = "http://www.ted.com/talks";
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(TEDUrl);
                webRequest.Method = "GET";

                //Start the request
                IAsyncResult token = webRequest.BeginGetResponse(new AsyncCallback(GetTEDTalksStreamCallback), webRequest);
            }
            catch (Exception e)
            {
                string msg = "Error: " + e.Message + ";" + e.ToString();
                MessageBox.Show(msg);
            }

            
        }

        /// <summary>
        /// Receive response stream from TED's server
        /// </summary>
        /// <param name="aysnchronousResult">The asynchronous result object</param>
        void GetTEDTalksStreamCallback(IAsyncResult asysnchronousResult)
        {

            HttpWebRequest webRequest = (HttpWebRequest)asysnchronousResult.AsyncState;
            
            //Get web response and
            WebResponse webResponse = ((HttpWebRequest)asysnchronousResult.AsyncState).EndGetResponse(asysnchronousResult);
            StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());

            //Save web response stream to responseString
            string responseString = streamReader.ReadToEnd();
            streamReader.Close();
            webResponse.Close();

            ParseHTML(responseString);
            listBox2.Dispatcher.BeginInvoke(new Action(delegate() { listBox2.ItemsSource = items; }));
  

        }

        /// <summary>
        /// Parse HTML from TED
        /// </summary>
        /// <param name="responseString">string returned from server</param>
        private void ParseHTML(string responseString)
        {
            //Begin parsing code
            int iFirst = responseString.IndexOf("<div class=\"talkListContainer");
            int iLast = responseString.IndexOf("<div class=\"pagination clearfix\">");
            int iLength = iLast - iFirst;
            responseString = responseString.Substring(iFirst, iLength);

            //Replace "&amp" by "&"
            string oldChar = "&amp";
            responseString = responseString.Replace(oldChar, "&");
            Console.Write(responseString);

            // Now, parse html to get Title & URL of each Talk
            string regexLinkPattern = @"<a.*?title=[""'](?<title>.*?)[""'].*?href=[""'](?<url>.*?)[""'].*?>.*?<img.*?<img.*?alt=[""'].*?[""'].*?src=[""'](?<imageUrl>.*?)[""'].*?/>";
            MatchCollection hyperlinkMatches = Regex.Matches(responseString, regexLinkPattern);

            string[] matchURL = new string[hyperlinkMatches.Count];
            string[] matchTitle = new string[hyperlinkMatches.Count];
            string[] matchImage = new string[hyperlinkMatches.Count];

            int i = 0;
            foreach (System.Text.RegularExpressions.Match match in hyperlinkMatches)
            {
                items.Add(new TEDVideo
                {
                    Title = match.Groups["title"].Value,
                    Url = match.Groups["url"].Value,
                    ImageUrl = new Uri(match.Groups["imageUrl"].Value, UriKind.Absolute)
                    
                });
                
                ++i;
            }


            string a = "2"; // testing purpose
        }
        

        private void Image_Tap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Video.xaml", UriKind.Relative));
        }

        private void Image_Hold(object sender, GestureEventArgs e)
        {

        }

        private void AddFavorite_Click(object sender, EventArgs e)
        {

        }

        private void AddPlaylist_Click(object sender, EventArgs e)
        {

        }

        private void PreviousPage_Click(object sender, EventArgs e)
        {

        }

        private void NextPage_Click(object sender, EventArgs e)
        {

        }

    }
}